<style lang="less">
.hmTechnician {
    .ivu-modal {
        width: 660px !important;
    }

    .pic {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;

        .pic-box {
            display: flex;
            justify-content: center;
            padding: 2px;
            box-sizing: border-box;
            align-items: center;
            width: 100px;
            height: 150px;
            line-height: 80px;
            margin-right: 10px;
            border: 1px dashed #2988f3;
            cursor: pointer;

            &:hover {
                transform: scale(1.02);
            }
        }

        .re-upload {
            width: 100%;
            flex: 1;
            color: #2e58d6;
            font-size: 13px;

            span {
                cursor: pointer;
            }
        }

        .pic-text {
            font-size: 13px;
            color: #cbcfd6;
        }
    }

    .ivu-checkbox-wrapper {
        margin: 5px !important;
    }
}
</style>
<template>
    <Modal v-model="show" :title="editTitle" class="hmTechnician" :mask-closable="false">
        <Form ref="hmTechnicianForm" :model="hmTechnicianForm" :rules="hmTechnicianFormRule" :label-width="100">
            <FormItem label="姓名" prop="name">
                <Input v-bind:disabled="disabled" type="text" :maxlength=50 v-model="hmTechnicianForm.name" placeholder="请输入姓名"/>
            </FormItem>
            <FormItem label="身份证号" prop="idCard">
                <Input v-bind:disabled="disabled" type="text" :maxlength=50 v-model="hmTechnicianForm.idCard" placeholder="请输入身份证号"/>
            </FormItem>
            <FormItem label="手机号" prop="mobile">
                <Input v-bind:disabled="disabled" type="text" :maxlength=50 v-model="hmTechnicianForm.mobile" placeholder="请输入手机号"/>
            </FormItem>
            <FormItem label="性别" prop="sex">
                <Select v-model="hmTechnicianForm.sex">
                    <Option value="女">女</Option>
                    <Option value="男">男</Option>
                </Select>
            </FormItem>
            <FormItem label="工作照" prop="workImg">
                <div class="pic">
                    <div class="pic-box" :style="{'border':hmTechnicianForm.workImg?'0 !important;':'auto'}" @click="upload">
                        <input ref="upload" type="file" accept="image/*" id="people-export" @change="inputChange" style="display: none;"/>
                        <Icon type="ios-add" size="24" color="#2988f3" v-if="!hmTechnicianForm.workImg"/>
                        <img :src="tempUrl" style="height: 100%;width: 100%;" v-else v-viewer="{movable: false}">
                    </div>
                    <div class="re-upload" v-if="hmTechnicianForm.workImg && !disabled">
                        <span @click="upload">重新上传</span>
                    </div>
                    <span class="pic-text" v-if="!disabled"
                          :style="{'width':hmTechnicianForm.workImg ?'100%':'auto'}">格式：png，尺寸：180*180px，不包含透明度</span>
                </div>
            </FormItem>

            <FormItem label="生活照" prop="cover">
                <div class="pic">
                    <div class="pic-box" :style="{'border':hmTechnicianForm.cover?'0 !important;':'auto'}" @click="uploadCover">
                        <input ref="uploadCover" type="file" accept="image/*"  @change="inputCoverChange" style="display: none;"/>
                        <Icon type="ios-add" size="24" color="#2988f3" v-if="!hmTechnicianForm.cover"/>
                        <img :src="coverTempUrl" style="height: 100%;width: 100%;" v-else v-viewer="{movable: false}">
                    </div>
                    <div class="re-upload" v-if="hmTechnicianForm.cover && !disabled">
                        <span @click="uploadCover">重新上传</span>
                    </div>
                    <span class="pic-text" v-if="!disabled"
                          :style="{'width':hmTechnicianForm.cover ?'100%':'auto'}">格式：png，尺寸：180*180px，不包含透明度</span>
                </div>
            </FormItem>
            <FormItem label="技师简介" prop="introduce">
                <Input v-bind:disabled="disabled" :rows="3" type="textarea" v-model="hmTechnicianForm.introduce" placeholder="请输入技师简介"/>
            </FormItem>
            <FormItem label="服务项目">
                <Checkbox :indeterminate="indeterminate" v-model="checkAll" @click.native="handleCheckAll">全选</Checkbox>
                <Divider size="small" class="ivu-m-0" />
                <CheckboxGroup v-model="hmTechnicianForm.projectList" @on-change="checkAllGroupChange">
                    <Checkbox v-for="(item,index) in projectDataList" :key="index" :label="item.id" border>{{item.title}}</Checkbox>
                </CheckboxGroup>
            </FormItem>

            <FormItem label="微信用户绑定">
                <Input readonly type="text" :maxlength=50 v-model="hmTechnicianForm.wxUserName" placeholder="请选择微信用户" @click.native="showUserList"/>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="show=false">取消</Button>
            <Button type="primary" :loading="loading" @click="handSubmit" v-if="!disabled">提交</Button>
        </div>

        <wxUserDrawer v-model="showUserDrawer" :checkedId="hmTechnicianForm.wxUserId" @getSelectedWords="getSelectedWords"></wxUserDrawer>
    </Modal>
</template>
<script>
import {addHmTechnician, updateHmTechnician, getHmTechnician} from '@/api/hmzd/hmTechnician'
import util from "@/libs/util";
import {queryAllHmProjectList} from "@/api/hmzd/hmProject";
import wxUserDrawer from "@/views/hmzd/components/wxUserDrawer";

export default {
    name: "updateHmTechnician",
    components: {wxUserDrawer},
    props: {
        value: {
            type: Boolean,
            default: false
        },
        HmTechnicianId: {
            type: String
        },
        modalTitle: {
            type: String
        }
    },
    data() {
        return {
            show: this.value,
            editTitle: this.modalTitle,
            loading: true,
            disabled: false,
            isWorkRadio: [],
            hmTechnicianForm: {
                name: '',
                introduce: '',
                idCard: '',
                sex: '',
                mobile: '',
                workImg: '',
                projectList: [],
                wxUserName: '',
                wxUserId: '',
            },
            hmTechnicianFormRule: this.getHmTechnicianFormRule(),
            tempUrl: "",
            coverTempUrl: "",
            projectDataList: [],
            indeterminate: false,
            checkAll: false,
            showUserDrawer: false
        }
    },
    methods: {
        handSubmit() {
            this.$refs['hmTechnicianForm'].validate((valid) => {
                this.loading = true;
                if (valid) {
                    if (this.HmTechnicianId != null && this.HmTechnicianId.trim().length > 0) {
                        this.hmTechnicianForm.id = this.HmTechnicianId;
                        updateHmTechnician(this.hmTechnicianForm).then(res => {
                            if (res.success) {
                                this.closeModal(false);
                                this.$emit('handSearch');
                                this.$Message.success('保存成功');
                            } else {
                                this.$Message.error(res.msg);
                            }
                        }).finally(() => {
                            this.loading = false;
                        });
                    } else {
                        addHmTechnician(this.hmTechnicianForm).then(res => {
                            if (res.success) {
                                this.closeModal(false);
                                this.$emit('handSearch');
                                this.$Message.success('保存成功');
                            } else {
                                this.$Message.error(res.msg);
                            }
                        }).finally(() => {
                            this.loading = false;
                        });
                    }
                } else {
                    this.loading = false;
                    this.$Message.error('表单验证不通过！');
                }
            });
        },
        closeModal(val) {
            this.$emit('input', val);
        },
        initForm() {
            this.hmTechnicianForm = {
                name: '',
                introduce: '',
                idCard: '',
                sex: '',
                mobile: '',
                workImg: '',
                projectList: [],
                wxUserName: '',
                wxUserId: '',
            };
        },
        getHmTechnicianFormRule() {
            return {
                name: [
                    {required: true, message: '姓名不能为空！', trigger: 'blur'},
                    {type: 'string', max: 50, message: '数据的最大长度为50！', trigger: 'blur'}
                ],
                idCard: [
                    {required: true, message: '身份证不能为空！', trigger: 'blur'},
                ],
                sex: [{required: true, message: '性别不能为空！', trigger: 'blur'},],
                mobile: [
                    {required: true, message: '手机号不能为空！', trigger: 'blur'},
                    {type: 'string', max: 50, message: '数据的最大长度为50！', trigger: 'blur'}
                ],
                workImg: [
                    {required: true, message: '工作照不能为空！', trigger: 'blur'},
                ]
            }
        },
        //图片上传
        inputChange(e) {
            const inputFile = this.$refs['upload'].files[0];
            let fileSize = inputFile.size;
            var size = fileSize / 2048;
            if (size > 2048) {
                this.$refs.upload.value = null;
                this.$Message.error('图片大小不能超过2M！');
                return;
            }
            if (size <= 0) {
                this.$refs.upload.value = null;
                this.$Message.error('图片大小不能为0M！');
                return;
            }
            let fileType = inputFile.type.toString().substring(inputFile.type.toString().lastIndexOf('/') + 1, inputFile.type.toString().length);
            if (fileType) {
                if (fileType.toLowerCase() != 'jpg' && fileType.toLowerCase() != 'jpeg' && fileType.toLowerCase() != 'png') {
                    this.$Message.error('附件格式不正确，请选择图片格式！');
                    this.$refs.upload.value = null;
                    return;
                }
            }
            let reader = new FileReader();
            reader.readAsDataURL(inputFile);
            reader.onload = () => {
                this.hmTechnicianForm.workImg = reader.result;
                this.tempUrl = reader.result;
                this.$refs.upload.value = null;
                this.$forceUpdate()
            }
        },
        inputCoverChange(e) {
            const inputFile = this.$refs['uploadCover'].files[0];
            let fileSize = inputFile.size;
            var size = fileSize / 2048;
            if (size > 2048) {
                this.$refs.uploadCover.value = null;
                this.$Message.error('图片大小不能超过2M！');
                return;
            }
            if (size <= 0) {
                this.$refs.uploadCover.value = null;
                this.$Message.error('图片大小不能为0M！');
                return;
            }
            let fileType = inputFile.type.toString().substring(inputFile.type.toString().lastIndexOf('/') + 1, inputFile.type.toString().length);
            if (fileType) {
                if (fileType.toLowerCase() != 'jpg' && fileType.toLowerCase() != 'jpeg' && fileType.toLowerCase() != 'png') {
                    this.$Message.error('附件格式不正确，请选择图片格式！');
                    this.$refs.uploadCover.value = null;
                    return;
                }
            }
            let reader = new FileReader();
            reader.readAsDataURL(inputFile);
            reader.onload = () => {
                this.hmTechnicianForm.cover = reader.result;
                this.coverTempUrl = reader.result;
                this.$refs.uploadCover.value = null;
                this.$forceUpdate()
            }
        },
        //点击上传图片
        upload() {
            if (this.disabled) {
                return;
            }
            this.$refs['upload'].dispatchEvent(new MouseEvent('click'));
        },
        uploadCover() {
            if (this.disabled) {
                return;
            }
            this.$refs['uploadCover'].dispatchEvent(new MouseEvent('click'));
        },
        async getProjectList() {
           await queryAllHmProjectList({}).then(res => {
                if(res.success) {
                    this.projectDataList = res.data;
                }
            })
        },
        handleCheckAll () {
            if (this.indeterminate) {
                this.checkAll = false;
            } else {
                this.checkAll = !this.checkAll;
            }
            this.indeterminate = false;

            if (this.checkAll) {
                const ids = Array.from(this.projectDataList,({ id }) => id);
                this.hmTechnicianForm.projectList = ids;
            } else {
                this.hmTechnicianForm.projectList = [];
            }
        },
        checkAllGroupChange (data) {
            if (data.length === this.projectDataList.length) {
                this.indeterminate = false;
                this.checkAll = true;
            } else if (data.length > 0) {
                this.indeterminate = true;
                this.checkAll = false;
            } else {
                this.indeterminate = false;
                this.checkAll = false;
            }
        },
        showUserList() {
            this.showUserDrawer = true
        },
        getSelectedWords(e) {
            this.hmTechnicianForm.wxUserId = e.id;
            this.hmTechnicianForm.wxUserName = e.nickname
        }
    },
    watch: {
        value(val) {
            this.show = val;
        },
        show(val) {
            this.initForm();
            this.loading = false;
            this.editTitle = this.modalTitle;
            if (this.editTitle == "查看") {
                this.disabled = true;
            } else {
                this.disabled = false;
            }
            if (val) {
                this.getProjectList();
                this.$refs['hmTechnicianForm'].resetFields();
                this.$refs['hmTechnicianForm'].id = null;
                if (this.HmTechnicianId != null && this.HmTechnicianId.trim().length > 0) {
                    getHmTechnician({id: this.HmTechnicianId}).then(res => {
                        if (res.success) {
                            if (res.data.workImg) {
                                this.tempUrl = util.nginxUrl + res.data.workImg;
                            }
                            if (res.data.cover) {
                                this.coverTempUrl = util.nginxUrl + res.data.cover;
                            }
                            this.hmTechnicianForm = res.data;
                            this.checkAllGroupChange(res.data.projectList ? res.data.projectList : [])
                        } else {
                            this.$Message.error(res.msg);
                        }
                    });
                }
            } else {
                this.closeModal(val);
            }
        }
    }
}
</script>
